$(document).ready(function () {

    // BOOTSTRAP TABLES USING FONT AWESOME ICONS
    // =================================================================
    // Require Bootstrap Table
    // http://bootstrap-table.wenzhixin.net.cn/
    //
    // =================================================================
    jQuery.fn.bootstrapTable.defaults.icons = {
        paginationSwitchDown: 'demo-pli-arrow-down',
        paginationSwitchUp: 'demo-pli-arrow-up',
        refresh: 'demo-pli-repeat-2',
        toggle: 'demo-pli-layout-grid',
        columns: 'demo-pli-check',
        detailOpen: 'demo-psi-add',
        detailClose: 'demo-psi-remove'
    }

    // EDITABLE - COMBINATION WITH X-EDITABLE
    // =================================================================
    // Require X-editable
    // http://vitalets.github.io/x-editable/
    //
    // Require Bootstrap Table
    // http://bootstrap-table.wenzhixin.net.cn/
    //
    // Require X-editable Extension of Bootstrap Table
    // http://bootstrap-table.wenzhixin.net.cn/
    // =================================================================
    $('#demo-editable').bootstrapTable({
        idField: 'id',
        method: 'PUT',
        url: '/order/read/list',
        singleSelect: true,
        columns: [
            {field: 'state', checkbox: true},
            {
                field: 'id',
                title: 'ID'
            }, {
                field: 'orderDate',
                title: '账单年月',
                editable: {
                    type: 'text'
                }
            }, {
                field: 'account',
                title: '类型'
            }, {
                field: 'phone',
                title: '手机号',
                editable: {
                    type: 'text'
                }
            }, {
                field: 'orgaName',
                title: '所属组织',
            }, {
                field: 'email',
                title: 'Email',
                editable: {
                    type: 'text'
                }
            }]
    });


    $.ajax({
        type: 'PUT',
        url: '/organization/read/list',
        data: JSON.stringify({keyword: ''}),
        success: function (ret) {
            var setting = {
                view: {
                    dblClickExpand: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: onClick
                }
            };

            function onClick(e, treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj('organizationTree'),
                    nodes = zTree.getSelectedNodes(),
                    v = "", n = "";
                nodes.sort(function compare(a, b) {
                    return a.id - b.id;
                });
                for (var i = 0, l = nodes.length; i < l; i++) {
                    v += nodes[i].id + ",";
                    n += nodes[i].name + ",";
                }
                if (v.length > 0) v = v.substring(0, v.length - 1);
                if (n.length > 0) n = n.substring(0, n.length - 1);
                $(".organizationValue").val(v);
                $(".organizationName").val(n);
            }

            $('.organizationBtn').click(function () {
                $(".organizationContent").show();
                $("body").bind("mousedown", onBodyDown);
            })

            function hideMenu() {
                $(".organizationContent").fadeOut("fast");
                $("body").unbind("mousedown", onBodyDown);
            }

            function onBodyDown(event) {
                if (!(event.target.class == "organizationBtn"
                    || event.target.class == "organizationContent"
                    || $(event.target).parents(".organizationContent").length > 0)) {
                    hideMenu();
                }
            }

            var data = ret.rows ? ret.rows : ret;
            for (var i = 0; i < data.length; i++) {
                data[i]['open'] = true;
                data[i]['pId'] = data[i].parentId;
                data[i]['name'] = data[i].orgaName;
            }
            var tree = $.fn.zTree.init($('#organizationTree'), setting, data);
        }
    });

    // BOOTSTRAP TABLE - CUSTOM TOOLBAR
    // =================================================================
    // Require Bootstrap Table
    // http://bootstrap-table.wenzhixin.net.cn/
    // =================================================================
    var $table = $('#demo-editable'), $remove = $('#demo-delete-row');

    $table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function () {
        $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);
    });

    $remove.click(function () {
        var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
            return row.id
        });
        $table.bootstrapTable('remove', {
            field: 'id',
            values: ids
        });
        $remove.prop('disabled', true);
    });

    new Switchery(document.getElementById('enable'));

    //本地验证未通过时提示
    $('#edit-form').data("validator-options", {
        invalid: function (form, errors) {
            $.each(errors, function (i, j) {
                alert(j);
            });
        },
        target: '#errtips'
    });
    $('#edit-form').validator($.extend({
        validClass: 'has-success',
        invalidClass: 'has-error',
        bindClassTo: '.form-group',
        formClass: 'n-default n-bootstrap',
        msgClass: 'n-right',
        stopOnError: true,
        display: function (elem) {
            return $(elem).closest('.form-group').find(".control-label").text().replace(/\*/, '').replace(/\:{0}：/, '').trim();
        },
        target: function (input) {
            var $formitem = $(input).closest('.form-group'),
                $msgbox = $formitem.find('span.msg-box');
            if (!$msgbox.length) {
                return [];
            }
            return $msgbox;
        },
        valid: function (ret) {
            //验证通过提交表单
            var params = $('#edit-form').serializeObject();
            params.password && (params.password = hex_md5(params.password));
            $.ajax({
                type: 'post',
                url: '/user',
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(params),
                success: function (d) {
                    if (d.code == '200') {
                        $table.bootstrapTable('refresh')
                        $('#demo-default-modal .close').click();
                        $.niftyNoty({
                            type: 'success',
                            title: '提示',
                            message: '添加成功',
                            container: 'floating',
                            timer: 5000
                        });
                    } else {
                        alert();
                    }
                }
            });
            return false;
        }
    }, $('#edit-form').data("validator-options") || {}));

    // 表单提交
    $('.btn-save').on('click', function () {
        $('#edit-form').submit();
    });
});


// FORMAT COLUMN
// Use "data-formatter" on HTML to format the display of bootstrap table column.
// =================================================================


// Sample format for Invoice Column.
// =================================================================
function invoiceFormatter(value, row) {
    return '<a href="#" class="btn-link" > Order #' + value + '</a>';
}


// Sample Format for User Name Column.
// =================================================================
function nameFormatter(value, row) {
    return '<a href="#" class="btn-link" > ' + value + '</a>';
}


// Sample Format for Order Date Column.
// =================================================================
function dateFormatter(value, row) {
    var icon = row.id % 2 === 0 ? 'fa-star' : 'fa-user';
    return '<span class="text-muted"><i class="fa fa-clock-o"></i> ' + value + '</span>';
}


// Sample Format for Order Status Column.
// =================================================================
function statusFormatter(value, row) {
    var labelColor;
    if (value == "Paid") {
        labelColor = "success";
    } else if (value == "Unpaid") {
        labelColor = "warning";
    } else if (value == "Shipped") {
        labelColor = "info";
    } else if (value == "Refunded") {
        labelColor = "danger";
    }
    var icon = row.id % 2 === 0 ? 'fa-star' : 'fa-user';
    return '<div class="label label-table label-' + labelColor + '"> ' + value + '</div>';
}


// Sample Format for Tracking Number Column.
// =================================================================
function trackFormatter(value, row) {
    if (value) return '<i class="fa fa-plane"></i> ' + value;
}


// Sort Price Column
// =================================================================
function priceSorter(a, b) {
    a = +a.substring(1); // remove $
    b = +b.substring(1);
    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
}